package com.macro.mall.portal.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.api.SMSSend;
import com.macro.mall.common.api.SMSSendCode;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.utils.Assist;
import com.macro.mall.mapper.RcRegistrationConventionMapper;
import com.macro.mall.model.RankVO;
import com.macro.mall.model.RcRegistrationContent;
import com.macro.mall.model.RcRegistrationConvention;
import com.macro.mall.model.UmsMember;
import com.macro.mall.portal.domain.MemberDetails;
import com.macro.mall.portal.service.RcRegistrationContentService;
import com.macro.mall.portal.service.RcRegistrationConventionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * RcRegistrationConvention的服务接口的实现类
 *
 * @author gaodx
 */
@Slf4j
@Service
public class RcRegistrationConventionServiceImpl implements RcRegistrationConventionService {

    private boolean isDebugEnabled;

    @Autowired
    private RcRegistrationConventionMapper rcRegistrationConventionMapper;
    // TODO 当你看到这个方法时你应该创建一个工具类做通用的方法,定义自己的返回格式化
    @Autowired
    private RcRegistrationContentService rcRegistrationContent;
    // TODO 当你看到这个方法时你应该创建一个工具类做通用的方法,定义自己的返回格式化

    @Override
    public List<RcRegistrationConvention> find(RcRegistrationConvention value, Integer pageNum, Integer pageSize) {
        //TODO这里可以做通过Assist做添加查询
        List<RcRegistrationConvention> result = null;
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy("create_time desc");
        Assist assist = new Assist();
        try {
            if (!StrUtil.isBlankIfStr(value.getHandleId())) {
                assist.andEq("handle_id", value.getHandleId());
            }
            if (!StrUtil.isBlankIfStr(value.getUserName())) {
                assist.andEq("user_name", value.getUserName());
            }
            if (!StrUtil.isBlankIfStr(value.getMobile())) {
                assist.andEq("mobile", value.getMobile());
            }
            result = rcRegistrationConventionMapper.selectRcRegistrationConvention(assist);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行获取RcRegistrationConvention数据集-->结果:", result);
        }
        return result;
    }

    @Override
    public RcRegistrationConvention findOne(Integer id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过RcRegistrationConvention的id获得RcRegistrationConvention对象-->失败:id不能为空");
            }
            Asserts.fail("执行通过RcRegistrationConvention的id获得RcRegistrationConvention对象-->失败:id不能为空");
        }
        RcRegistrationConvention result = null;
        try {
            result = rcRegistrationConventionMapper.selectRcRegistrationConventionById(id);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过RcRegistrationConvention的id获得RcRegistrationConvention对象-->结果:", result);
        }
        return result;
    }

    @Override
    public CommonResult saveNotNull(RcRegistrationConvention value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行将RcRegistrationConvention中属性值不为null的数据保存到数据库-->失败:对象不能为空");
            }
            Asserts.fail("失败:对象不能为空");
        }
        int result = 0;
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
            UmsMember umsMember = memberDetails.getUmsMember();
            RcRegistrationConvention build = RcRegistrationConvention.builder()
                    .userId(umsMember.getId().intValue())
                    .userName(umsMember.getName())
                    .mobile(umsMember.getUsername())
                    .communityName(umsMember.getCommunityName())
                    .floor(umsMember.getFloor())
                    .handleId(value.getHandleId()).build();
            result = rcRegistrationConventionMapper.insertNotNullRcRegistrationConvention(build);
            RcRegistrationContent one = rcRegistrationContent.findOne(value.getHandleId());
            int length = one.getTitle().length() / 2;
            int i = one.getAddr().length() / 3;
           /* SMSSend.sendSMS(umsMember.getUsername(),
                    SMSSendCode.rcregistration.getMasage().replaceAll("xname1",one.getTitle().substring(0,length)).replaceAll("xname2",one.getTitle().substring(length))
                            .replaceAll("xtime", DateUtil.format(one.getStime(), "yyyy-MM-dd")+"-"+ DateUtil.format(one.getEtime(), "yyyy-MM-dd"))
                            .replaceAll("xcontent1",one.getAddr().substring(0,i))
                            .replaceAll("xcontent2",one.getAddr().substring(i, i*2))
                            .replaceAll("xcontent3",one.getAddr().substring(i*2))
                            .replaceAll("xphone",one.getMobile()),
                    SMSSendCode.rcregistration.getCode());*/
            SMSSend.sendSMS(umsMember.getUsername(),
                    SMSSendCode.rcregistration.getMasage()
                            .replaceAll("xname",one.getTitle())
                            .replaceAll("xstime", DateUtil.format(one.getStime(), "yyyy-MM-dd"))
                            .replaceAll("xetime", DateUtil.format(one.getEtime(), "yyyy-MM-dd"))
                            .replaceAll("xcontent",one.getAddr())
                            //.replaceAll("xphone",one.getMobile()),
                            .replaceAll("xphone","010-60770118"),
                    SMSSendCode.rcregistration.getCode());
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行将RcRegistrationConvention中属性值不为null的数据保存到数据库-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult updateNotNullById(RcRegistrationConvention value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行通过RcRegistrationConvention的id更新RcRegistrationConvention中属性不为null的数据-->失败:对象为null");
            }
            Asserts.fail("执行通过RcRegistrationConvention的id更新RcRegistrationConvention中属性不为null的数据-->失败:对象为null");
        }
        int result = 0;
        try {
            result = rcRegistrationConventionMapper.updateNotNullRcRegistrationConventionById(value);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过RcRegistrationConvention的id更新RcRegistrationConvention中属性不为null的数据-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult deleteById(Integer id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过RcRegistrationConvention的id删除RcRegistrationConvention-->失败:id不能为空");
            }
            Asserts.fail("执行通过RcRegistrationConvention的id删除RcRegistrationConvention-->失败:id不能为空");
        }
        int result = 0;
        try {
            result = rcRegistrationConventionMapper.deleteRcRegistrationConventionById(id);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过RcRegistrationConvention的id删除RcRegistrationConvention-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public String rank() {
        List<RankVO> result = null;
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
            Long userId = memberDetails.getUmsMember().getId();
            result = rcRegistrationConventionMapper.rank();
            for(RankVO one : result) {
                if(one.getUserId().equals(userId.toString())) {
                    String no = one.getRankNo() > 1000 ? "1000+": one.getRankNo().toString();
                    return no;
                }
            }
            return "1000+";

        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过RcRegistrationConvention的id删除RcRegistrationConvention-->结果:", result);
        }
        return null;
    }


}